package com.micro.school.h5.util;

import com.alibaba.fastjson2.JSONObject;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @description:
 * @author: xoko
 * @create: 2024/5/16  17:50
 **/
public class DesUtil {

    // 字符编码
    public static final String CHARSET_UTF8 = "UTF-8";
    // 加密算法DES
    public static final String DES = "DES";
    // 电话本模式
    public static final String DES_ECB = "DES/ECB/PKCS5Padding";
    // 加密块链模式--推荐
    public static final String DES_CBC = "DES/CBC/PKCS5Padding";

    //    偏移变量，固定占8位字节
    private final static String IV_PARAMETER = "12345678";


    private static Key generateKey(String password) throws Exception {
        DESKeySpec dks = new DESKeySpec(password.getBytes(CHARSET_UTF8));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        return keyFactory.generateSecret(dks);
    }

    /**
     * DES加密字符串--ECB格式
     *
     * @param password
     *            加密密码，长度不能够小于8位
     * @param data
     *            待加密字符串
     * @return 加密后内容
     */
    public static String encryptECB(String password, String data) {
        if (password == null || password.length() < 8) {
            throw new RuntimeException("加密失败，key不能小于8位");
        }
        if (data == null) {
            return null;
        }
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(DES_ECB);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom());
            byte[] bytes = cipher.doFinal(data.getBytes(CHARSET_UTF8));
            // JDK1.8及以上可直接使用Base64，JDK1.7及以下可以使用BASE64Encoder
            return new String(Base64.encodeBase64(bytes));

        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }

    /**
     * DES解密字符串--ECB格式
     *
     * @param password
     *            解密密码，长度不能够小于8位
     * @param data
     *            待解密字符串
     * @return 解密后内容
     */
    public static String decryptECB(String password, String data)
            throws Exception {
        Key secretKey = generateKey(password);
        Cipher cipher = Cipher.getInstance(DES_ECB);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, new SecureRandom());
        return new String(cipher.doFinal(Base64.decodeBase64(data.getBytes(CHARSET_UTF8))), CHARSET_UTF8);
    }


    /**
     * DES加密字符串-CBC加密格式
     *
     * @param password
     *            加密密码，长度不能够小于8位
     * @param data
     *            待加密字符串
     * @return 加密后内容
     */
    public static String encryptCBC(String password, String data) {
        try {
            Key secretKey = generateKey(password);
            Cipher cipher = Cipher.getInstance(DES_CBC);
            IvParameterSpec spec = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET_UTF8));
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, spec);
            byte[] bytes = cipher.doFinal(data.getBytes(CHARSET_UTF8));
            return new String(Base64.encodeBase64(bytes));
        } catch (Exception e) {
            e.printStackTrace();
            return data;
        }
    }

    /**
     * DES解密字符串--CBC格式
     *
     * @param password
     *            解密密码，长度不能够小于8位
     * @param data
     *            待解密字符串
     * @return 解密后内容
     */
    public static String decryptCBC(String password, String data)
            throws Exception {
        Key secretKey = generateKey(password);
        Cipher cipher = Cipher.getInstance(DES_CBC);
        IvParameterSpec spec = new IvParameterSpec(IV_PARAMETER.getBytes(CHARSET_UTF8));
        cipher.init(Cipher.DECRYPT_MODE, secretKey, spec);
        return new String(cipher.doFinal(Base64.decodeBase64(data.getBytes(CHARSET_UTF8))), CHARSET_UTF8);
    }

    public static void main(String[] args) throws Exception {
//        Map<String, String> paramsMap = new TreeMap<String, String>();
//        paramsMap.put("merchant_id", "800000000858");
//        paramsMap.put("merchant_name","");
//        paramsMap.put("merchant_order_no", "12335");
//        paramsMap.put("nonce_str", "20221108083525");
//        paramsMap.put("req_trace_id", "20221108083525");
//        paramsMap.put("order_infos", "学生餐费");
//        paramsMap.put("return_url", "www.baidu.com");
//        paramsMap.put("staff_name", "1001");
//        paramsMap.put("success_url", "www.sina.com");
//        paramsMap.put("total_amount", "1");
//        String resStr = com.hanhui.wel.api.sdk.SDKUtil.createLinkString(paramsMap, false, true, "utf-8");
//        String key = "7UDL8BM6";
//        String data = "merchant_id=800000000948&merchant_name=历城区想得美百货&staff_name=18906440222&req_trace_id=1&term_no=1000000000&merchant_order_no=S2408174882638836325222635&total_amount=0.01&pay_way=1&notify_url=www.baidu.com";
//        System.out.println(data);
//        String string1 = encryptECB(key, data);
//        System.out.println(string1);
//        String deSt1 = decryptECB(key, string1);
//        System.out.println(deSt1);
//        Map<String, String> bizData = new HashMap<>();
////        bizData = SDKUtil.filterBlank(bizData);
//        bizData.put("txtcode","1001");
//        bizData.put("req_date","20241108081332");
//        bizData.put("sign",string1);
////        bizData = SDKUtil.filterBlank(bizData);
        Map<String, String> paramsMap = new TreeMap<String, String>();
        paramsMap.put("merchant_id", "800000000858");
//        paramsMap.put("merchant_name","");
        paramsMap.put("merchant_order_no", "4165525626312300");
        paramsMap.put("nonce_str", "20221108083526");
        paramsMap.put("req_trace_id", "20221108083526");
        paramsMap.put("order_infos", "订单");
        paramsMap.put("return_url", "www.baidu.com");
        paramsMap.put("staff_name", "1001");
        paramsMap.put("success_url", "www.sina.com");
        paramsMap.put("total_amount", "1.00");
        String resStr = SDKUtil.createLinkString(paramsMap, false, true, "utf-8");
        Map<String, String> bizData = new HashMap<>();
        bizData.put("txtcode","1001");
        bizData.put("req_date","20241108081332");
        bizData.put("sign",DesUtil.encryptECB("2MMB8UL3",resStr));
        String result = HttpUtil.sendPostRequest(bizData, "https://fapi.leyibei.com/cashiersystem/ycmobileapi/pay");
        JSONObject job=JSONObject.parseObject(result);
        String aaa=job.getString("sign");
        String deSt1 = decryptECB("2MMB8UL3", aaa);
        System.out.println(deSt1);


//        Map<String, String> map=new HashMap<String, String>();
//        Map<String, String> paramsMap = new TreeMap<String, String>();
//        paramsMap.put("merchant_id", "800000000858");
//        paramsMap.put("merchant_order_no","4165525626312336");
//        paramsMap.put("req_trace_id","6628551456456");
//        paramsMap.put("staff_name", "1001");
//        String resStr = SDKUtil.createLinkString(paramsMap, false, true, "utf-8");
//        Map<String, String> bizData = new HashMap<>();
//        bizData.put("txtcode","1001");
//        bizData.put("req_date",String.valueOf(System.currentTimeMillis()));
//        bizData.put("sign", DesUtil.encryptECB("2MMB8UL3",resStr));
//        String result = null;
//
//            result = HttpUtil.sendPostRequest(bizData, "http://localhost:8089/cashiersystem/ycmobileapi/query");
//
//        JSONObject job=JSONObject.parseObject(result);
//        String response=job.getString("response");
//        String code =JSONObject.parseObject(response).getString("code");
//        String msg =JSONObject.parseObject(response).getString("msg");
//        if(code.equals("000000")){
//            String sign=job.getString("sign");
//            String deSt1 = DesUtil.decryptECB("2MMB8UL3", sign);
//            JSONObject resultobj=JSONObject.parseObject(deSt1);
//            String out_order_no=resultobj.getString("out_order_no");
//            String order_state=resultobj.getString("order_state");
//            if(null!=order_state&&!order_state.equals("")&&null!=out_order_no&&!out_order_no.equals("")){
//                if(order_state.equals("S")){
//
//                }
//            }
//            System.out.println(deSt1);
//        }else{
//            System.out.println(123);
//        }

//        orderRecordsVo.setChannelOrderNo(UUID.randomUUID().toString().replace("-", ""));
//        Map<String, String> map=new HashMap<String, String>();
//        Map<String, String> paramsMap = new TreeMap<String, String>();
//        paramsMap.put("merchant_id", "800000000858");
//        paramsMap.put("merchant_order_no", "4165525626312336");
//        paramsMap.put("req_trace_id","416496551455488445455");
//        paramsMap.put("staff_name", "1001");
//        paramsMap.put("refund_money", "0.01");
//        paramsMap.put("refund_type", "1");
//        paramsMap.put("nonce_str", UUID.randomUUID().toString().replace("-", ""));
//        String resStr = SDKUtil.createLinkString(paramsMap, false, true, "utf-8");
//        Map<String, String> bizData = new HashMap<>();
//        bizData.put("txtcode","1001");
//        bizData.put("req_date",String.valueOf(System.currentTimeMillis()));
//        bizData.put("sign", DesUtil.encryptECB("2MMB8UL3",resStr));
//        String result = null;
//        try {
//            result = HttpUtil.sendPostRequest(bizData, "http://localhost:8089/cashiersystem/ycmobileapi/refund");
//        } catch (URISyntaxException e) {
//            throw new RuntimeException(e);
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        JSONObject job=JSONObject.parseObject(result);
//        String response=job.getString("response");
//        String code =JSONObject.parseObject(response).getString("code");
//        String msg =JSONObject.parseObject(response).getString("msg");
//        String sign=job.getString("sign");
//        String deStr = DesUtil.decryptECB("2MMB8UL3", sign);
//        if(code.equals("000000")){
////            String sign=job.getString("sign");
////            String deStr="";
//            try {
//                deStr = DesUtil.decryptECB("2MMB8UL3", sign);
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
//            JSONObject resultobj=JSONObject.parseObject(deStr);
//            String out_order_no=resultobj.getString("out_order_no");
//            String order_state=resultobj.getString("order_state");
//            if(null!=order_state&&!order_state.equals("")&&null!=out_order_no&&!out_order_no.equals("")){
//                if(order_state.equals("S")){
////                    orderRecordsVo.setStatus("4");
////                    orderRecordsService.updateOrderRecords(orderRecordsVo);
//                    //添加余额 待商量
//                }
//            }
//            map.put("code","0000");
//        }else{
//            map.put("code","0001");
//            map.put("msg",msg);
//        }




    }

}
